package com.jia.leetcode2.array;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: designPattern
 * @description:
 * @author: STU756
 * @create: 2021-03-25 13:31
 */
public class TwoSum {
    //Numbers is not sort
    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < numbers.length; i++) {
            int x = target - numbers[i];
            if(map.containsKey(x)){
                return new int[]{map.get(x), i};
            }
            map.put(numbers[i], i);
        }
        return new int[]{};
    }

    /**
     * 使用二分查找
     * @param numbers sorted array
     * @param target
     * @return
     */
    public int[] twoSum2(int[] numbers, int target) {
        for(int i = 0; i < numbers.length; i++) {
            int j = bsearch(numbers, target - numbers[i], i + 1);
            if(j != -1) {
                return new int[]{i, j};
            }
        }
        return new int[]{};
    }

    private int bsearch(int[] numbers, int target, int start) {
        int l = start, r = numbers.length - 1;
        while(l < r) {
            int mid = (l + r) >> 1;
            if(numbers[mid] >= target) {
                r = mid;
            }else {
                l = mid + 1;
            }
        }
        return (l == r && numbers[l] == target)? l : -1;
    }

    /**
     * 双指针
     * Time:O(N) Space:O(1)
     * @param numbers sorted array
     * @param target
     * @return
     */
    public int[] twoSum3(int[] numbers, int target) {
        for(int i = 0, j = numbers.length - 1; i < j; ) {
            if(numbers[i] + numbers[j] == target) {
                return new int[]{i, j};
            }else if(numbers[i] + numbers[j] > target) {
                --j;
            }else {
                ++i;
            }
        }
        return new int[] {};
    }
}
